package com.hui.web.servlet;

import com.hui.base.Constants;
import com.hui.base.StatusCode;
import com.hui.pojo.Course;
import com.hui.service.CourseService;
import com.hui.service.impl.CourseServiceImpl;
import com.hui.utils.DateUtils;
import com.hui.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 李昭辉
 * @Date: 2021/07/12/15:11
 * @Description: 课程营销信息修改与保存 , 涉及到文件上传，所以基础 HttpServlet 类
 */
@WebServlet("/courseSalesInfo")
public class CourseSalesInfoServlet extends HttpServlet {
    private CourseService courseService = new CourseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            Course course = new Course();
            HashMap<String, Object> map = new HashMap<>();
            // 创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // 创建文件上传核心对象
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            // 解析request对象,获取请求体中的所有数据
            List<FileItem> itemList = upload.parseRequest(req);
            for (FileItem item : itemList) {
                boolean flag = item.isFormField();
                if (flag) {
                    // 普通表单处理 : 获取结果，放入map中
                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString("UTF-8");
                    map.put(fieldName, fieldValue);
                } else {
                    // 上传文件处理 :
                    String fileName = item.getName();
                    String newFileName = UUIDUtils.getUUID() + "_" + fileName;
                    // 获取服务器路径  C:\apache-tomcat-8.5.55\webapps\lagou_edu_home
                    String realPath = this.getServletContext().getRealPath("/");
                    // 去除服务器路径最后的工程名  C:\apache-tomcat-8.5.55\webapps\
                    String path = realPath.substring(0, realPath.indexOf("lagou_edu_home"));
                    // 获取文件输入流
                    InputStream in = item.getInputStream();
                    // 创建文件输出流
                    FileOutputStream out = new FileOutputStream(path + "/upload/" + newFileName);
                    // 开始上传文件
                    in.transferTo(out);
                    // 关闭资源
                    out.close();
                    in.close();
                    // 保存图片的url信息，可直接通过该url访问图片
                    map.put("course_img_url", Constants.LOCAL_URL + "/upload/" + newFileName);
                }
            }
            // 使用BeanUtils将map中的数据全部封装到course对象中
            BeanUtils.populate(course, map);
            // 添加操作不用id, 修改操作带id
            Object id = map.get("id");
            String dateTime = DateUtils.getDateFormat();
            PrintWriter writer = resp.getWriter();
            // 添加操作
            if (id == null) {
                // 补全信息 ,  创建时间、修改时间、状态
                course.setCreate_time(dateTime);
                course.setUpdate_time(dateTime);
                course.setStatus(1);
                // 调用业务层,获取结果状态码，并返回出去
                String statusCode = courseService.saveCourseSaleInfo(course);
                writer.write(statusCode);
            } else {// 修改操作
                // 补全信息 ,  修改时间
                course.setUpdate_time(dateTime);
                // 调用业务层,获取结果状态码，并返回出去
                String statusCode = courseService.updateCourseSaleInfo(course);
                writer.write(statusCode);
            }
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
